<template>
  <div ref="mainCon" class="container">
    <topTitle
      v-if="!hiddleToolBar"
      :titleText="titleText"
      :titleExplain="titleExplain"
    ></topTitle>
    <div class="mainCon">
      <el-row
        v-if="loginType === 'QY' || loginType === 'XM'"
        class="searchBox searchInputWidth"
      >
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="保证金类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.type"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in cashDepositOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item>
            <!-- <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="commonBtn"
            ></el-button> -->
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <!-- <el-button class="commonBut saveBtn funComBut bzjAddJc" icon="icon iconfont icontianjia" @click="toAdd">
						<span class="opetareText">添加</span>
					</el-button> -->
        </el-form>
      </el-row>
      <el-row v-else class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="accountForm">
          <el-col :lg="8" :xl="6">
            <el-form-item label="监管区域" class="row-padding-bottom">
              <el-cascader
                ref="manageArea"
                v-model="areaId"
                :options="areasOptions"
                @change="getAreaId"
                clearable
                filterable
                :props="{ checkStrictly: true }"
                placeholder="请选择"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="缴纳项目" class="row-padding-bottom">
              <el-input
                placeholder="请输入项目名称"
                clearable
                v-model="filterField.projectName"
              ></el-input>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="缴纳单位" class="row-padding-bottom">
                <el-input
                  placeholder="请输入单位名称"
                  clearable
                  v-model="filterField.companyName"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="保证金类型" class="row-padding-bottom">
                <el-select
                  v-model="filterField.type"
                  filterable
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in cashDepositOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="状态" class="row-padding-bottom">
                <el-select
                  v-model="filterField.status"
                  filterable
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item>
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchTable"
              v-sdc
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icondaochu"
            v-sdc
            @click="exportList"
          >
            <span class="opetareText">导出</span>
          </el-button>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div
          style="margin-bottom: 24px"
          v-if="loginType === 'QY' || loginType === 'XM'"
        >
          <el-button
            class="commonBut saveBtn funComBut bzjAddJc"
            icon="icon iconfont icontianjia"
            @click="toAdd"
          >
            <span class="opetareText">添加</span>
          </el-button>
        </div>
        <!-- 列表 -->
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          @sort-change="sortChange"
          :data="tableData"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column label="项目名称" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.projectName"
                :columnName="'projectName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            label="缴纳单位"
            v-if="loginType === 'JC'"
            width="230"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                :columnName="'companyName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeDesc"
            label="保证金类型"
            :formatter="formatTd"
            min-width="150"
            :filterField="[
              { text: '履约保证金', value: '履约保证金' },
              { text: '工程质量保证金', value: '工程质量保证金' },
            ]"
            :filter-method="filterHandler"
          ></el-table-column>
          <el-table-column
            prop="cashTotal"
            label="现金形式保证金（元）"
            sortable="custom"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            prop="bankTotal"
            label="银行保函保证金（元）"
            sortable="custom"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            prop="insuranceTotal"
            label="商业保险保证金（元）"
            sortable="custom"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            prop="tripartiteTotal"
            label="第三方担保保证金（元）"
            sortable="custom"
            :formatter="formatTd"
            min-width="220"
          ></el-table-column>
          <el-table-column
            prop="statusDesc"
            label="状态"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="shouldReturnDate"
            label="现金保证金应退日期"
            sortable="custom"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            prop="actReturnDate"
            label="实际退还日期"
            sortable="custom"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            align="left"
            label="操作"
            fixed="right"
            min-width="250"
            v-if="loginType === 'QY' || loginType === 'XM'"
          >
            <template slot-scope="scope">
              <el-link type="primary" @click="toDetail(scope.row)"
                >查看详情</el-link
              >
              <span>
                <el-link
                  v-if="scope.row.status == 'RETURN'"
                  type="primary"
                  @click="toCancelRefund(scope.row)"
                  >撤销退还</el-link
                >
                <el-link
                  v-if="scope.row.status == 'DEPOSIT'"
                  type="primary"
                  @click="toReturn(scope.row)"
                  >退还</el-link
                >
                <el-link type="primary" @click="toDelete(scope.row)"
                  >删除</el-link
                >
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            label="操作"
            fixed="right"
            width="110"
            v-else
          >
            <template slot-scope="scope">
              <el-link type="primary" @click="toDetail(scope.row)"
                >查看详情</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      title="确认退还"
      :visible.sync="dialogVisible"
      @close="closeDialog"
      custom-class="dialog-minwidth"
      width="640px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      class="oneColumnDialog"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="120px"
        class="demo-ruleForm"
        style="padding-top: 8px"
      >
        <el-form-item label="实际退还日期：" prop="actReturnDate">
          <el-date-picker
            type="date"
            placeholder="请选择实际日期"
            v-model="formData.actReturnDate"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="退还凭证：">
          <uploadAnnex
            @getFileList="getFileList"
            :limitationFactor="limitationFactor"
            @getFile="getFile"
            :upLoadFile="formData.upLoadFile"
          />
        </el-form-item>
        <el-row>
          <el-col :span="24" v-model="formData.upLoadFile">
            <uploadResult
              style="margin-left: 120px !important"
              :resultList="formData.upLoadFile"
              @callBackResult="getFile"
            />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog" class="cancel">取 消</el-button>
        <el-button
          v-sdc
          type="primary"
          class="save"
          @click.native="saveEventType"
          :loading="isSaveLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import common from '../../kits/common'
import scrollTable from '../../mixin/scrollTable'

export default {
  name: 'threeTermsCashDeposit',
  mixins: [scrollTable],
  data() {
    return {
      titleText: '三项保证金',
      titleExplain:
        '查看辖区内各区域项目的招标、履约、工程质量保证金缴纳及退还情况',
      advanced: false,
      cashDepositOptions: [],
      statusOptions: [],
      requestUrl: 'api-d/trinomial/expand/list',
      loading: true,
      isShow: false,
      tableData: [], //表格数据
      areaId: '', //区域
      filterField: {
        areaId: '',
        projectName: '',
        companyName: '',
        type: '',
        status: '',
      },
      pageSize: 20,
      pageNo: 1,
      dialogVisible: false,
      formData: {
        actReturnDate: '',
        upLoadFile: [], //附件
      },
      formRules: {
        actReturnDate: [
          {
            required: true,
            message: '实际日期不能为空',
            trigger: 'change',
          },
        ],
      },
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M', //自定义报错提示语
        methodTip:
          '合同附件支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      srcList: [],
      oldSrcList: [],
      isSaveLoading: false, //弹框保存loading
      id: '', //主键id
      userType: '',
    }
  },
  computed: { ...mapState(['areasOptions', 'industryOptionsNC']) },
  created() {
    this.loginType = localStorage.getItem('loginType')
    //获取区域
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.filterField.areaId = this.areaId
    this.getTypeOption()
    this.getStateOption()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.titleExplain =
      this.loginType === 'QY' || this.loginType === 'XM'
        ? '填报招标、履约、工程质量保证金缴纳及退还情况'
        : '查看辖区内各区域项目的招标、履约、工程质量保证金缴纳及退还情况'
  },
  activated() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  methods: {
    ...mapActions(['getAreas', 'getIndustryNC']),
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getTypeOption() {
      this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/type',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.cashDepositOptions = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    getStateOption() {
      this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/status',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.statusOptions = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //列表查询
    searchTable() {
      this.pageSize = 20
      this.pageNo = 1
      this.$refs.pagination.getTableListData()
    },
    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.filterField.areaId = areaId
    },
    //跳转详情
    toDetail(row) {
      this.$router.push({
        path: '/home/cashDeposit/threeTermsCashDepositDetail',
        name: 'threeTermsCashDepositDetail',
        query: {
          id: row.id,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/cashDeposit/threeTermsCashDeposit',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    // 导出
    exportList() {
      if (this.tableData.length > 0) {
        window.location.href =
          common.commonApi +
          'api-d/trinomial/expand/export?areaId=' +
          this.filterField.areaId +
          '&projectName=' +
          encodeURIComponent(this.filterField.projectName) +
          '&companyName=' +
          this.filterField.companyName +
          '&type=' +
          this.filterField.type +
          '&status=' +
          this.filterField.status +
          '&sort=' +
          this.filterField.sort +
          '&sortField=' +
          this.filterField.sortField +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        this.$message({
          type: 'error',
          message: '无数据导出',
        })
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    //跳转详情
    toDetail(row) {
      this.$router.push({
        path: '/home/cashDeposit/threeTermsCashDepositDetail',
        name: 'threeTermsCashDepositDetail',
        query: {
          id: row.id,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/cashDeposit/threeTermsCashDeposit',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toAdd() {
      this.$router.push({
        path: '/home/cashDeposit/threeTermsCashDepositAdd',
        name: 'threeTermsCashDepositAdd',
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/cashDeposit/threeTermsCashDeposit',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toDelete(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delCashDeposit(row)
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        })
    },
    delCashDeposit(row) {
      this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/delete',
        data: {
          id: row.id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    toCancelRefund(row) {
      this.$confirm('撤销退还后将清除退还数据，您确定要撤销退还吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.toCancelRefundDeposit(row)
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        })
    },
    //撤销
    toCancelRefundDeposit(row) {
      this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/rescind',
        data: {
          id: row.id,
          optType: 'cx',
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '撤销退还成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    closeDialog() {
      this.dialogVisible = false
      this.$refs.formData.resetFields()
      this.formData.actReturnDate = ''
      this.formData.upLoadFile = []
    },
    toReturn(row) {
      this.dialogVisible = true
      this.id = row.id
    },
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    getFile(val) {
      this.formData.upLoadFile = val
    },
    saveEventType() {
      this.isSaveLoading = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.save()
        } else {
          this.isSaveLoading = false
          return false
        }
      })
    },
    save() {
      this.axios({
        method: 'post',
        url: 'api-d/trinomial/expand/rescind',
        data: {
          id: this.id,
          actReturnDate: this.formData.actReturnDate,
          fileBack: JSON.stringify(this.formData.upLoadFile),
          optType: 'ht',
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.dialogVisible = false
            this.isSaveLoading = false
            this.$message.success('退还成功')
            this.$nextTick(function () {
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            })
          } else {
            this.isSaveLoading = false
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
          this.$message.error(error.response.data)
        })
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  top: 209px;
}
@import '../../../static/css/filterArea.less';
</style>
